package it.unina.ingswdemo.services;

import it.unina.ingswdemo.beans.Image;
import it.unina.ingswdemo.persistence.PMF;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ShowImage extends HttpServlet {

	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		showImage(req, resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		showImage(req, resp);
	}
	
	private void showImage(HttpServletRequest req, HttpServletResponse resp){
		
//		byte[] imgStream= ProvaUploadNOblobServlet.img;
		
		
		//Inizio recupero immagine dal datastore
		String id = req.getParameter("id");
		Image img = getImage(Long.parseLong(id));
		
		
		if (img != null && img.getImageType() != null &&
				img.getImage() != null) {
            // Set the appropriate Content-Type header and write the raw bytes
            // to the response's output stream
            resp.setContentType(img.getImageType());
            try {
				resp.getOutputStream().write(img.getImage());
				resp.getOutputStream().flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        } else {
            // If no image is found with the given title, redirect the user to
            // a static image
           
        }
	}

	
	private Image getImage(long id) {
	    PersistenceManager pm = PMF.get().getPersistenceManager();

	    // Search for any Movie object with the passed-in title; limit the number
	    // of results returned to 1 since there should be at most one movie with
	    // a given title
	    Query query = pm.newQuery(Image.class, "key == idParam");
	    query.declareParameters("long idParam");
	    query.setRange(0, 1);

	    try {
	        List<Image> results = (List<Image>) query.execute(id);
	        if (results.iterator().hasNext()) {
	            // If the results list is non-empty, return the first (and only)
	            // result
	            return results.get(0);
	        }
	    } finally {
	        query.closeAll();
	        pm.close();
	    }

	    return null;
	}
}